#PC端控制LED灯

#2.创建UDP_socket 客户端
#3.接收UDP数据
#4.根据UDP数据控制LED
import _thread
import time
import machine
from ctrl import *
import sys

def test_led(*args, **kwargs):
    #创建LED对象
    pin2 = machine.Pin(2,machine.Pin.OUT)
    while True:
        pin2.value(1)
        time.sleep(1)
        pin2.value(0)       
        time.sleep(1)

def test_wait(*args, **kwargs):
    while True:
        print("等待中。。。")
        time.sleep(2)
        
#链接网络
def do_connect():
    import network
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('HUIQINBO', 'adis123456')
        i = 1
        
        while not wlan.isconnected():
            print("正在连接网络中.....{}".format(i))   #format()  不是 format{}
            time.sleep(1)
    print('network config:', wlan.ifconfig())

def create_udp_socket():
    import socket
    #创建udp置换字
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    local_addr = ('', 7788)  # ip地址和端口号，ip一般不用写，表示本机的任何一个ip
    udp_socket.bind(local_addr)
    return udp_socket

def main():
    do_connect()
    #2.创建UDP_socket
    udp_socket = create_udp_socket()
    print("创建UDP_socket成功")
    
    # 向服务器发送数据
    udp_socket.sendto("hello".encode(), ("192.168.43.49", 3030))
    print("发送测试数据hello给上位机")
    time.sleep_ms(1000)
    #3.接收UDP数据      
    while True:
        
        recv_data,sender_info = udp_socket.recvfrom(1024)
        print("{}发送的数据：{}".format(sender_info,recv_data))
        
        recv_data_str = recv_data.decode("utf-8")
        print("解码后的数据：{}".format(recv_data_str))
    
    
        #4.根据UDP数据控制LED
        if recv_data_str == "left":
            left()
            print("left")
        elif recv_data_str == "right":
            right()
            print("right")
        elif recv_data_str == "run":
            forward()
            print("run")
        elif recv_data_str == "stop":
            print("stop")
        elif recv_data_str == "thread":
            print("thread start!!")
            thread_led = _thread.start_new_thread(test_led, (1,))
            thread_wait = _thread.start_new_thread(test_wait, (1,))
        elif recv_data_str == "exit":
            thread_led.exit()
            thread_wait.exit()
            udp_socket.sendto("quit...".encode(), ("192.168.43.49", 3030))
            print("exit!!")
if __name__ == "__main__":
    main()


